package com.baomidou.kaptcha;

import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_DATE;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author fuwei
 * @since 2019-05-31
 */
public class HttpSessionCacheImpl implements Cache {

    @Autowired
    private HttpServletRequest request;

    @Override
    public String get(String key) {
        HttpSession httpSession = request.getSession(false);
        Object code = httpSession.getAttribute(KAPTCHA_SESSION_KEY);
        if (ObjectUtils.isEmpty(code)) {
            return null;
        }
        long sessionTime = Long.valueOf(String.valueOf(httpSession.getAttribute(getExpiredKey(key))));
        long duration = (System.currentTimeMillis() - sessionTime) / 1000;
        if (duration < 0) {
            throw new KaptchaTimeoutException();
        }
        return String.valueOf(code);
    }

    @Override
    public boolean set(String key, String code, int expires) {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute(key, code);
        httpSession.setAttribute(getExpiredKey(key), System.currentTimeMillis() + expires);
        return true;
    }

    @Override
    public boolean delete(String key) {
        HttpSession httpSession = request.getSession(false);
        httpSession.removeAttribute(key);
        return false;
    }

    /**
     * 生成过期key
     * @param key
     * @return
     */
    private String getExpiredKey(String key) {
        StringBuilder sb = new StringBuilder(KAPTCHA_SESSION_DATE);
        if (!ObjectUtils.isEmpty(key)) {
            sb.append("_").append(key);
        }
        return sb.toString();
    }

}
